const { app, Menu, BrowserWindow, Tray } = require('electron')
const path = require('path')

app.whenReady().then(() => {
  createMenu()
  createTray()
  createDockMenu()
  popupMenu()
})

const tpl = [
  {
    label: '自定义菜单',
    submenu: [
      {
        label: '点我试试',
        click: () => {
          console.log('try')
        },
      },
      {
        label: '默认选中',
        type: 'checkbox',
        checked: true,
      },
      { type: 'separator' },
      {
        label: '单选菜单',
        submenu: [
          { label: '选项1', type: 'radio' },
          { label: '选项2', type: 'radio' },
          { label: '选项3', type: 'radio' },
        ],
      },
      {
        label: '多级菜单',
        submenu: [
          {
            label: '二级菜单',
            submenu: [{ label: '三级菜单', submenu: [{ label: '四级菜单' }] }],
          },
        ],
      },
    ],
  },
  {
    label: '调试菜单',
    submenu: [
      { role: 'toggleDevTools' },
      {
        role: 'reload',
        accelerator: 'Shift+K',
        click: () => {
          console.log('reload')
        },
      },
    ],
  },
]

function createMenu() {
  // Mac 系统要把第一个菜单的位置留出来
  const template = [...tpl]
  if (process.platform === 'darwin') {
    template.unshift({ label: '' })
  }
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

let tray
function createTray() {
  tray = new Tray(path.join(__dirname, 'phoneTemplate.png'))
  const contextMenu = Menu.buildFromTemplate(tpl)
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    console.log('tray clicked')
  })
}

function createDockMenu() {
  const { dock } = app
  const menu = Menu.buildFromTemplate(tpl)
  dock.setMenu(menu)
}

let win
function popupMenu() {
  win = new BrowserWindow({
    width: 600,
    height: 500,
  })
  win.loadFile(path.join(__dirname, '../renderer/index.html'))
  const menu = Menu.buildFromTemplate(tpl)
  setTimeout(() => {
    menu.popup({
      callback: () => {
        console.log('menu closed')
      },
    })
  }, 3000)
}
